# -*- coding: utf-8 -*-
# File : test.py
# Author: taoyahui
# Date : 2022/5/23

# 示例1练习：通过Jinja2实现变量的渲染
# from jinja2 import Environment, BaseLoader
# template_str = """你好, {{ name }}"""
#
# my_string = "世界"
# tpl = Environment(loader=BaseLoader).from_string(template_str)
# data = tpl.render(name=my_string)
# print(data)


# 示例2练习: 通过jinja2实现复杂变量的渲染
from jinja2 import Environment, BaseLoader
from flask import Flask, request
app = Flask(__name__) # 创建一个Flask对象

def generate_jinja():
    template_str = """{% for name in names %}
                        {% if name=='张三'%} 你好, {{ name }}
                        {% endif %}
                      {% endfor %}"""
    tpl = Environment(loader=BaseLoader).from_string(template_str)
    data = tpl.render(names=['张三','李四', '王五', '赵六'])
    print(data)
    return data

def generate_name(name):
    template_str = """你好, {{ name }}"""
    tpl = Environment(loader=BaseLoader).from_string(template_str)
    data = tpl.render(name=name)
    print(data)
    return data

@app.route('/')
def root():
    return "hello world"

@app.route('/gen_jinja', methods=['GET'])
def my_jinja():
    data = generate_jinja()
    return data

@app.route('/gen_jinja_name', methods=['GET'])
def my_jinja_name():
    name = request.args['name']
    data = generate_name(name)
    return data

if __name__ == '__main__':
    app.run(host='0.0.0.0')